package com.bigluo.service.impl;

import com.alibaba.fastjson.JSON;
import com.bigluo.api.BaseResponse;
import com.bigluo.api.req.QryUsrInfoReq;
import com.bigluo.api.req.SaveUsrInfoReq;
import com.bigluo.api.rsp.QryAllUsrInfoRsp;
import com.bigluo.api.rsp.QryUsrInfoRsp;
import com.bigluo.common.enums.ERedisCachePrefix;
import com.bigluo.dao.domain.User;
import com.bigluo.dao.mappers.UserMapper;
import com.bigluo.service.UserService;
import com.bigluo.util.Assert;
import com.bigluo.util.redis.IRedisCacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by luojun on 2017/8/30.
 */
@Service("userService")
public class UsrServiceImpl implements UserService {
    private Logger logger = LoggerFactory.getLogger(UsrServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IRedisCacheService redisCacheService;
    public QryUsrInfoRsp qryUsrInfo(QryUsrInfoReq req) {
        QryUsrInfoRsp rsp = new QryUsrInfoRsp();
        //1 从redis中查询
        User user = redisCacheService.getVal(ERedisCachePrefix.GET_USRINF_BYID,req.getId()+"",User.class);
        if(user == null) {
            user = userMapper.qryUsrInfById(new Integer(req.getId()));
            redisCacheService.setVal(ERedisCachePrefix.GET_USRINF_BYID,req.getId()+"",user);
        }
        Assert.notNull(user,"TEM0001","用户信息不存在");
        BeanUtils.copyProperties(user,rsp);
        return rsp;
    }

    public BaseResponse saveUsrInfo(SaveUsrInfoReq req) {
        User user = new User();
        BeanUtils.copyProperties(req,user);
        int result = userMapper.save(user);
        Assert.isTrue(result==1,"保存用户数失败","TMP00003");
        BaseResponse rsp = new BaseResponse();
        rsp.setRspCode("TMP00000");
        rsp.setRspMsg("操作成功");
        return rsp;
    }

    public QryAllUsrInfoRsp qryAllUsrInfo() {
        List<User> userList = userMapper.qryAllUsrInfo();
        QryAllUsrInfoRsp rsp = new QryAllUsrInfoRsp();
        rsp.setUserList(userList);
        rsp.setRspCode("TMP00000");
        rsp.setRspMsg("查询成功");
        return rsp;
    }
}
